package com.x.client.bean

import android.graphics.Region
import android.os.Parcelable
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.gg.utils.DateUtils
import com.gg.utils.isNullOrZero
import com.google.gson.annotations.SerializedName
import com.x.client.R
import com.x.client.bean.options.RadarOption
import kotlinx.android.parcel.IgnoredOnParcel
import kotlinx.android.parcel.Parcelize
import java.math.BigDecimal
import java.util.*
import kotlin.collections.ArrayList


/**
 *  Creator : GG
 *  Time    : 2017/11/22
 *  Mail    : gg.jin.yu@gmail.com
 *  Explain :
 */
@Parcelize
data class Car(
        @SerializedName("brand") var brand: Brand? = null,
        @SerializedName("brandId") var brandId: Int? = 0, //2
        @SerializedName("car4sUpkeepState") var car4sUpkeepState: Int? = 0, //1
        @SerializedName("carAgeRemark") var carAgeRemark: String? = "", //1年内
        @SerializedName("carAuthState") var carAuthState: Int? = 0, //1
        @SerializedName("carBargainPriceState") var carBargainPriceState: Int? = 0, //0
        @SerializedName("carBusinessInsuranceDate") var carBusinessInsuranceDate: Long? = null, //1510675200000
        @SerializedName("carCreateTime") var carCreateTime: Long? = null, //1510710772000
        @SerializedName("carDetectState") var carDetectState: Int? = 0, //2
        @SerializedName("carDisplacement") var carDisplacement: String? = null, //3.6T
        @SerializedName("carInletModel") var carInletModel: String? = "", //3.6T
        @SerializedName("carEnviron") var carEnviron: String? = "", //国IV
        @SerializedName("carFixedPriceState") var carFixedPriceState: Int? = 0, //0
        @SerializedName("carFlawDesc") var carFlawDesc: String? = "--", //工工工工工
        @SerializedName("carFloorPrice") var carFloorPrice: Double? = 0.0, //5.5
        @SerializedName("carForceInsuranceDate") var carForceInsuranceDate: Long? = null, //交强险
        @SerializedName("carFuel") var carFuel: String? = "", //汽油
        @SerializedName("carGearbox") var carGearbox: String? = "", //自动
        @SerializedName("carGuidePrice") var carGuidePrice: Double? = 0.0, //6
        @SerializedName("carId") var carId: String? = "", //123
        @SerializedName("carImages") var carImages: ArrayList<CarImage>? = arrayListOf(),
        @SerializedName("carImage") var carImage: CarImage? = null,
        @SerializedName("carImageUrl") var carImageUrl: String? = null,//http://47.93.47.216:8083/group1/M00/00/01/wKgAvFoSqo2AbAxVAAGLtchij08999.png
        @SerializedName("carInColor") var carInColor: String? = "", //其它
        @SerializedName("carKeyNum") var carKeyNum: Int? = null, //4
        @SerializedName("carLicenceDate") var carLicenceDate: Long? = null, //1510675200000
        @SerializedName("carLicenceState") var carLicenceState: Int? = 1, //0
        var carLicenceStr: String? = null,
        @SerializedName("carLocationCityName") var carLocationCityName: String? = "", //北京
        @SerializedName("carMileage") var carMileage: BigDecimal? = null, //2
        @SerializedName("carMortgageDesc") var carMortgageDesc: String? = "--", //木林要要
        @SerializedName("carMortgageState") var carMortgageState: Int? = 0, //0
        @SerializedName("carOrderState") var carOrderState: Int? = 0, //1
        @SerializedName("carOutColor") var carOutColor: String? = "", //其它
        @SerializedName("carPlate") var carPlate: String? = "", //京A88888
        @SerializedName("carRedAge") var carRedAge: Int? = 0, //45
        @SerializedName("carRemark") var carRemark: String? = "", //nbnbnbbnb
        @SerializedName("carRetailPrice") var carRetailPrice: Double? = 0.0, //5.8
        @SerializedName("carSiteState") var carSiteState: Int? = 0, //2
        @SerializedName("carPledgeState") var carPledgeState: Int? = 0, //2
        @SerializedName("carSaleState") var carSaleState: Int? = 0, //2
        @SerializedName("carSaleTime") var carSaleTime: Long? = 0, //2
        @SerializedName("carSellingPointDesc") var carSellingPointDesc: String? = "--", //哈哈哈 这是一个卖点描述
        @SerializedName("carStockState") var carStockState: Int? = 0, //2
        @SerializedName("carTitle") var carTitle: String? = "", //nbnb
        @SerializedName("carTransferState") var carTransferState: Int? = 0, //0
        @SerializedName("carType") var carType: BaseCarTypeOptions? = BaseCarTypeOptions(),
        @SerializedName("carTypeId") var carTypeId: Int? = null, //2
        @SerializedName("carPurpose") var carPurpose: Int? = CarPurpose_Not_Operations, //2
        @SerializedName("carUpdateTime") var carUpdateTime: Long? = 0, //1510800840000
        @SerializedName("carValidateDate") var carValidateDate: Long? = null, //1510675200000
        @SerializedName("carVin") var carVin: String? = null, //123
        @SerializedName("carVin6") var carVin6: String? = "", //123
        @SerializedName("carYellowAge") var carYellowAge: Int? = 0, //30
        @SerializedName("marketId") var marketId: String? = "", //138
        @SerializedName("market") var market: Market? = null, //138
        @SerializedName("model") var model: Model? = Model(),
        @SerializedName("modelId") var modelId: Int? = 0, //4
        @SerializedName("region") var region: Region? = Region(),
        @SerializedName("regionId") var regionId: String? = "", //17111017295895539072265639535439
        @SerializedName("series") var series: Series? = Series(),
        @SerializedName("seriesId") var seriesId: Int? = 0, //2
        @SerializedName("shop") var shop: Shop? = Shop(),
        @SerializedName("shopId") var shopId: String? = "", //17111013065235254074399782052879
        @SerializedName("stockAgeRemark") var stockAgeRemark: String? = "", //30～60天
        @SerializedName("userId") var userId: String? = "", //1
        @SerializedName("carVehicletaxDate") var carVehicletaxDate: Long? = null,//车船税有效时间
        @SerializedName("carTransferNum") var carTransferNum: Int? = null,//过户次数
        @SerializedName("carDoorNum") var carDoorNum: Int? = null,//过户次数
        @SerializedName("carRadarInfo") var carRadarInfo: CarRadar? = null,//过户次数
        @SerializedName("carExtendedWarranty") var carExtendedWarranty: Int? = 0,//延保服务
        @SerializedName("carFinanceService") var carFinanceService: Int? = 0,//金融服务
        @SerializedName("saleUserId") var saleUserId: String? = null,//销售人员
        @SerializedName("user") var user: User? = User(),//过户次数
        var modelConf: ArrayList<ModelConf> = arrayListOf(),
        var confBus: ConfBus = ConfBus(),
        var carConfIds: Array<String>? = emptyArray(),
        var type: Int = Item,
        var isSelect: Boolean = false
) : MultiItemEntity, Parcelable {

    override fun getItemType(): Int = type


    fun subtitle(): String {
        return getMileageStr() + (if (getMileageStr().isNullOrBlank()) "" else "/") + getTime() + "/${shop?.shopName}"
    }

    fun getMileageStr(): String =
            when {
                carMileage == null -> "未输入里程"
                carMileage?.compareTo(BigDecimal(0)) == 0 -> "未输入里程"
                carMileage?.compareTo(BigDecimal(0.1)) == -1 -> "${(carMileage?.multiply(BigDecimal(10000)))?.stripTrailingZeros()?.toPlainString()}公里"
                else -> "${carMileage?.setScale(2, BigDecimal.ROUND_HALF_UP)?.stripTrailingZeros()?.toPlainString()}万公里"
            }


    fun carVinStr(): String = "车架号 : $carVin"

    @IgnoredOnParcel
    var brandSeriesModel: String? = null
        get() = brand?.brandName + series?.seriesName + model?.modelName

    fun getCarLicenceDate(): String? = if (carLicenceDate.isNullOrZero()) null else DateUtils.date2YearAndMonth(Date(carLicenceDate
            ?: 0))

    //交强险日期
    fun getCarForceInsuranceDate(): String? = if (carForceInsuranceDate.isNullOrZero()) null else DateUtils.date2YearAndMonth(Date(carForceInsuranceDate
            ?: 0))

    //商业险日期
    fun getCarBusinessInsuranceDate(): String? = if (carBusinessInsuranceDate.isNullOrZero()) null else DateUtils.date2YearAndMonth(Date(carBusinessInsuranceDate
            ?: 0))

    //年审日期
    fun getCarValidateDate(): String? = if (carValidateDate.isNullOrZero()) null else DateUtils.date2YearAndMonth(Date(carValidateDate
            ?: 0))

    fun getCarKeyNum(): String? =
            when (carKeyNum) {
                1 -> "1把"
                2 -> "2把"
                3 -> "3把"
                4 -> "4把"
                else -> "请选择钥匙数量"
            }


    fun getCarPurpose(): String? =
            when (carPurpose) {
                CarPurpose_Operations -> "营运"
                CarPurpose_Not_Operations -> "非营运"
                CarPurpose_To_Not_Operations -> "营转非"
                else -> "请选择使用性质"
            }

    fun getTransfer(): String? =
            when (carTransferState) {
                0 -> "不包含过户费"
                1 -> "包含过户费"
                else -> ""
            }

    fun getPrice(): String = "￥${carRetailPrice}万"

    fun getFixedPrice(): String? =
            when (carFixedPriceState) {
                0 -> "不是一口价"
                1 -> "是一口价"
                else -> ""
            }

    fun getTransferAndFixedPrice(): String = "${getTransfer()} | ${getFixedPrice()}"

    fun getLicenseStr() =
            when (carLicenceState) {
                CarLicenceState_Licence_Plate -> "已经上牌"
                CarLicenceState_No_Licence_Plate -> "未上牌"
                CarLicenceState_New_Car -> "新车"
                else -> ""
            }

    fun getTime() =
            when (carLicenceState) {
                CarLicenceState_Licence_Plate -> {
                    if (carLicenceDate != null) {
                        getCarLicenceDate()?.substring(0, 4) + "年"
                    } else ""
                }
                CarLicenceState_No_Licence_Plate -> "未上牌"
                CarLicenceState_New_Car -> "新车"
                else -> "未上牌"
            }

    fun getStock(): String =
            when (carStockState) {
                CarStockState_Fail_In_Warehouse -> "未完成入库"
                CarStockState_Reject -> "审核驳回"
                CarStockState_Undo -> "撤销入库"
                CarStockState_Apply_In_Warehouse -> "入库审核"
                CarStockState_In_Warehouse -> "已入库"
                CarStockState_Apply_Out_Warehouse -> "出库审核中"
                CarStockState_Out_Warehouse -> "已出库"
                else -> "--"
            }

    fun getCarStatus(): String {
        val sb = StringBuffer()

        sb.append(when (carStockState) {
            CarStockState_Fail_In_Warehouse -> "未完成入库"
            CarStockState_Reject -> "审核驳回"
            CarStockState_Undo -> "撤销入库"
            CarStockState_Apply_In_Warehouse -> "入库审核"
            CarStockState_In_Warehouse -> when (carSaleState) {
                CarSaleState_On_Shelve -> "上架中"
                CarSaleState_Already_Shelve -> "已上架"
                CarSaleState_Remove_Shelve -> "已下架"
                else -> "已入库"
            }
            CarStockState_Apply_Out_Warehouse -> "出库审核中"
            CarStockState_Out_Warehouse -> "已出库"
            else -> "--"
        })
                .append("/")
                .append(when (carAuthState) {
                    CarAuthState_No_Verified -> {
                        when (carDetectState) {
                            CarDetectState_Not_Detect -> "未初检"
                            CarDetectState_Not_Pass_Detect -> "初检未通过"
                            CarDetectState_Pass_Detect -> "初检通过"
                            CarDetectState_Apply_Retest -> "申请复检中"
                            CarDetectState_Pass_Retest -> "复检完成"
                            else -> "--"
                        }
                    }
                    CarAuthState_Verified -> "已认证"
                    else -> "--"
                })

        return sb.toString()
    }

    fun getDetectStateStr(): Int =
            when (carDetectState) {
                CarDetectState_Not_Detect -> R.string.not_detect
                CarDetectState_Pass_Detect -> R.string.pass_detect
                CarDetectState_Not_Pass_Detect -> R.string.not_pass_detect
                CarDetectState_Apply_Retest -> R.string.applying_retest
                CarDetectState_Pass_Retest -> R.string.pass_retest
                else -> R.string.pass_retest
            }


    fun getDetectStateColor(): Int =
            when (carDetectState) {
                CarDetectState_Not_Detect -> R.color.text_yellow
                CarDetectState_Pass_Detect -> R.color.text_green
                CarDetectState_Not_Pass_Detect -> R.color.text_red
                CarDetectState_Apply_Retest -> R.color.text_yellow
                CarDetectState_Pass_Retest -> R.color.text_green
                else -> R.color.text_green
            }


    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as Car

        if (carId != other.carId) return false

        return true
    }

    override fun hashCode(): Int {
        return carId?.hashCode() ?: 0
    }


    val marketInfo: String
        get() = "${market?.city?.cityName} ${shop?.shopName}"


    val radarData: RadarOption
        get() = RadarOption().apply {


            val transfer: Double = when {
                carRadarInfo?.carTransferNum ?: 0 >= 10 -> 0.0
                carRadarInfo?.carTransferNum ?: 0 <= 0 -> 10.0
                else -> 10 - (carRadarInfo?.carTransferNum?.toDouble() ?: 0.0)
            }

            val retailPrice: Double = when {
                carRadarInfo?.carRetailPrice ?: 0.0 >= 80.0 -> 0.0
                carRadarInfo?.carRetailPrice ?: 0.0 <= 0.0 -> 80.0
                else -> 80 - (carRadarInfo?.carRetailPrice ?: 0.0)
            }

            val carAge: Double = when {
                carRadarInfo?.carAge ?: 0 >= 15 -> 0.0
                carRadarInfo?.carAge ?: 0 <= 0 -> 15.0
                else -> 15 - (carRadarInfo?.carAge?.toDouble() ?: 0.0)
            }

            val displacement: Double = when {
                carRadarInfo?.carDisplacement ?: 0.0 >= 6 -> 6.0
                carRadarInfo?.carDisplacement ?: 0.0 <= 0 -> 0.0
                else -> carRadarInfo?.carDisplacement ?: 0.0
            }

            val mileage: Double = when {
                carRadarInfo?.carMileage ?: 0.0 >= 20 -> 0.0
                carRadarInfo?.carMileage ?: 0.0 <= 0 -> 20.0
                else -> 20 - (carRadarInfo?.carMileage ?: 0.0)
            }

            legend = RadarOption.Legend(data = listOf("预算分配（Allocated Budget）"))
            radar = RadarOption.Radar(name = RadarOption.Radar.Name(textStyle = RadarOption.Radar.Name.TextStyle(color = "#fff", backgroundColor = "#999", borderRadius = 3, padding = listOf(3, 5))),
                    indicator = listOf(
                            RadarOption.Radar.Indicator(name = "排量", max = 6),
                            RadarOption.Radar.Indicator(name = "车龄", max = 15),
                            RadarOption.Radar.Indicator(name = "里程", max = 20),
                            RadarOption.Radar.Indicator(name = "价格", max = 80),
                            RadarOption.Radar.Indicator(name = "过户", max = 10)
                    ))
            series = listOf(RadarOption.Series(name = "", type = "radar",
                    data = listOf(RadarOption.Series.Data(label = RadarOption.Series.Data.Label(show = false, fontSize = 25),
                            value = listOf(
                                    displacement,
                                    carAge,
                                    mileage,
                                    retailPrice,
                                    transfer
                            )))))
        }

    var displacement: String = carDisplacement.toString() + carInletModel

    fun getCarInfo(): List<CarInfo> {
        return listOf(CarInfo(title = "外观颜色", info = if (carOutColor.isNullOrBlank()) "--" else carOutColor),
                CarInfo(title = "内饰颜色", info = if (carInColor.isNullOrBlank()) "--" else carInColor),
                CarInfo(title = "是否4S店保养", info = if (car4sUpkeepState == 1) "是" else "否"),
                CarInfo(title = "车身类型", info = if (carType?.carTypeName.isNullOrBlank()) "--" else carType?.carTypeName),
                CarInfo(title = "排量", info = if ((carDisplacement.toString() + carInletModel).isNullOrBlank()) "--" else carDisplacement.toString() + carInletModel),
                CarInfo(title = "变速箱", info = if (carGearbox.isNullOrBlank()) "--" else carGearbox),
                CarInfo(title = "燃油类型", info = if (carFuel.isNullOrBlank()) "--" else carFuel),
                CarInfo(title = "排放标准", info = if (carEnviron.isNullOrBlank()) "--" else carEnviron),
                CarInfo(title = "年审到期日", info = if (getCarValidateDate().isNullOrBlank()) "--" else getCarValidateDate()),
                CarInfo(title = "交强险到期日", info = if (getCarForceInsuranceDate().isNullOrBlank()) "--" else getCarForceInsuranceDate()),
                CarInfo(title = "商业险到期日", info = if (getCarBusinessInsuranceDate().isNullOrBlank()) "--" else getCarBusinessInsuranceDate()),
                CarInfo(title = "--", info = "--")
        )
    }

    data class CarInfo(var title: String? = null, var info: String? = null)

    companion object {
        //已上架
        const val CarSaleState_Already_Shelve = 20
        //未上架
        const val CarSaleState_Not_On_Shelve = 0
        //上架中
        const val CarSaleState_On_Shelve = 10
        //已下架
        const val CarSaleState_Remove_Shelve = 30

        const val Title = 0x0011
        const val Item = 0x0022

        //已经上牌
        const val CarLicenceState_Licence_Plate = 1
        //未上牌
        const val CarLicenceState_No_Licence_Plate = 2
        //新车
        const val CarLicenceState_New_Car = 3

        //已预定
        const val CarOrderState_Already = 1
        //未预定
        const val CarOrderState_No_Already = 0

        //特卖
        const val CarBargainPriceState_Sale = 1
        //不是特卖
        const val CarBargainPriceState_No_Sale = 0

        //已认证
        const val CarAuthState_Verified = 10
        //未认证
        const val CarAuthState_No_Verified = 0

        //入库申请中
        const val CarStockState_Apply_In_Warehouse = 10
        //未完成入库
        const val CarStockState_Fail_In_Warehouse = 0
        //入库审核驳回
        const val CarStockState_Reject = 1
        //撤销入库
        const val CarStockState_Undo = 2

        //在库车辆
        const val CarStockState_In_Warehouse = 20
        //出库审核中
        const val CarStockState_Apply_Out_Warehouse = 30
        //出库车辆
        const val CarStockState_Out_Warehouse = 40

        //未入场 场地
        const val CarSiteState_Not_In_Site = 400
        //已入场
        const val CarSiteState_Already_In_Site = 410
        //出场审核中
        const val CarSiteState_Apply_Out_Site = 420
        //出场审核通过
        const val CarSiteState_Apply_Success_Out_Site = 430
        //已出场
        const val CarSiteState_Out_Site = 440

        //未抵押
        const val CarPledgeState_Not_Pledge = 300
        //已抵押
        const val CarPledgeState_Already_Pledge = 310

        //未检测
        //500	未初检
        const val CarDetectState_Not_Detect = 500
        //510	初检不通过
        const val CarDetectState_Not_Pass_Detect = 510
        //520	初检通过
        const val CarDetectState_Pass_Detect = 520
        //530	申请复检中
        const val CarDetectState_Apply_Retest = 530
        //540	复检完成
        const val CarDetectState_Pass_Retest = 540

        //抵押图片
        const val CarImage_Mortgage = 1
        //含Vin的图片
        const val CarImage_Vin = 2
        //不含Vin的图片
        const val CarImage_Not_Vin = 3
        //营运
        const val CarPurpose_Operations = 1
        //非营运
        const val CarPurpose_Not_Operations = 2
        //营转非
        const val CarPurpose_To_Not_Operations = 3


    }

}
//抵押状态(carPledgeState)300：未抵押状态、310：抵押状态
//上架状态(carSiteState) 400 未入场 410 已入场 420 出场审核中 430 出场审核通过 440 已出场
//上架状态(carSaleState) 0 初始化 10 申请上架 20 上架 30 下架
//检测状态(carDetectState) 0 初始化 10 检测中 20 检测完毕
//库存状态(carStockState) 0 初始化 10 入库审核 20 入库 30 出库审核 40 出库
//认证状态(carAuthState) 0 未认证 10 已认证
//500	未初检
//510	初检不通过
//520	初检通过
//530	申请复检中
//540	复检完成